//
//  AppDelegate.m
//  sqliteToEnity
//
//  Created by hament on 13-7-29.
//  Copyright (c) 2013年 hament. All rights reserved.
//

#import "AppDelegate.h"
#import "HCoreConfig.h"
#import "HSqlManager.h"
#import "TableEnity.h"
#import "AttributeEnity.h"
#import "DragTextField.h"
#import "SqliteToEnityController.h"
#import "BFImage.h"
#import "PlistJsonVC.h"
#import "TutorialWindowController.h"
//#import <CoreServices/CoreServices.h>
@implementation AppDelegate



static NSString* const kVarSysInfoVersionFormat  = @"%@.%@.%@ (%@)";
static NSString* const kVarSysInfoKeyOSVersion = @"kern.osrelease";
static NSString* const kVarSysInfoKeyOSBuild   = @"kern.osversion";

- (NSString *) _strControlEntry:(NSString *)ctlKey {
    
    size_t size = 0;
    if ( sysctlbyname([ctlKey UTF8String], NULL, &size, NULL, 0) == -1 ) return nil;
    
    char *machine = calloc( 1, size );
    
    sysctlbyname([ctlKey UTF8String], machine, &size, NULL, 0);
    NSString *ctlValue = [NSString stringWithCString:machine encoding:[NSString defaultCStringEncoding]];
    
    free(machine); return ctlValue;
}

- (NSString *) getOSVersionInfo {
    
    NSString *darwinVer = [self _strControlEntry:kVarSysInfoKeyOSVersion];
    NSString *buildNo = [self _strControlEntry:kVarSysInfoKeyOSBuild];
    if ( !darwinVer || !buildNo ) return nil;
    
    NSString *majorVer = @"10", *minorVer = @"x", *bugFix = @"x";
    NSArray *darwinChunks = [darwinVer componentsSeparatedByCharactersInSet:[NSCharacterSet punctuationCharacterSet]];
    
     debugLog(@"darwinChunks:%@",darwinChunks);
    
    if ( [darwinChunks count] > 0 ) {
        
        NSInteger firstChunk = [(NSString *)[darwinChunks objectAtIndex:0] integerValue];
        minorVer = [NSString stringWithFormat:@"%ld", (firstChunk - 4)];
        bugFix = [darwinChunks objectAtIndex:1];
        debugLog(@"firstChunk:%ld",firstChunk);
    }
    
    
    //return [NSString stringWithFormat:kVarSysInfoVersionFormat, majorVer, minorVer, bugFix, buildNo];
    
    NSString * v=[NSString stringWithFormat:kVarSysInfoVersionFormat, majorVer, minorVer, bugFix, buildNo];
    debugLog(@"vvv:%@",v);
    
     return [NSString stringWithFormat:@"%@.%@", majorVer, minorVer];
    
}


#pragma mark ----------layloading--------
-(PlistJsonVC*)plistJsonVC{

    if (!_plistJsonVC) {
        _plistJsonVC=[[PlistJsonVC alloc] initWithNibName:@"PlistJsonVC" bundle:nil];
        _plistJsonVC.view.frame=NSMakeRect(200, 0, 775, 700);
    }


    return _plistJsonVC;
}


-(NSMutableSet*)controllerSet{
    
    if (!_controllerSet) {
        _controllerSet=[NSMutableSet set];
    }
    
    return _controllerSet;
}

#pragma mark ----------appdelegate--------

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    //
    NSImage * image=[[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"view_bg6" ofType:@"png"]];
    [self.sideImageView setImage:image];
    
    //share
    
    
    
    
    //datasource
    [[self.toolBox titleCell] setTextColor:[NSColor orangeColor]];
    [[self.supportBox titleCell] setTextColor:[NSColor orangeColor]];
    [[self.shareBox titleCell] setTextColor:[NSColor orangeColor]];
    ///*获取系统版本号
//    NSProcessInfo *pInfo = [NSProcessInfo processInfo];
//    NSString *plversion = [pInfo operatingSystemVersionString];
//    debugLog(@"plversion:%@",plversion);

    
    
    NSDictionary *pversion = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"];
    NSString *productVersion = [pversion objectForKey:@"ProductVersion"];
    NSLog (@"productVersion =========== %@", productVersion);
    
    
    //如果系统版本大于10.7,才能使用分享功能
    NSString *version =[self getOSVersionInfo];
    debugLog(@"osx version:%f",[version floatValue]);
    if ([version compare:@"10.7" options:NSNumericSearch]) {
        
        [self.shareBox setHidden:NO];
    } else {
        
        [self.shareBox setHidden:YES];
        
    }
    
    // NSInteger  osname = [pInfo operatingSystem];
     //NSAppKitVersionNumber
     // debugLog(@"osx version:%f",systemVersion);
   


 
    
    // Insert code here to initialize your application

    //tableview的数据源,如果用了cocoabingding,不要写在awakefromnib里,不然会引起kvc触发顺序不对
    //[self.functionTable numberOfRows];
    _functionDataSource=@[@{@"name": @"Sqlite export to Entity",@"image": [NSImage imageNamed:@"enity_Bg"]},
                          @{@"name": @"Sqlite export to Plist",@"image": [NSImage imageNamed:@"plistBg"]},
                          @{@"name": @"Sqlite export to Json",@"image": [NSImage imageNamed:@"jsonBg"]}];
    [self.functionTable insertRowsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, _functionDataSource.count)]
                              withAnimation:NO];
    
    
    _supportDataSource=@[@{@"name": @"how to use",@"image":[NSImage imageNamed:@"userGuide"]},
                          @{@"name": @"Give suggestion",@"image": [NSImage imageNamed:NSImageNameUserAccounts]},
                          @{@"name": @"Info",@"image": [NSImage imageNamed:NSImageNameInfo]}];
    //@{@"name": @"Share",@"image": [NSImage imageNamed:@"btn_share_s"]}
    
    [self.supportTable insertRowsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, _supportDataSource.count)]
                              withAnimation:NO];
    
    self.sqlVC=[[SqliteToEnityController alloc] initWithNibName:@"SqliteToEnityController" bundle:nil];
    self.sqlVC.view.frame=NSMakeRect(200, 0, 775, 700);
    [self.window.contentView addSubview:self.sqlVC.view];
    [self.window makeFirstResponder:self.sqlVC.sqlitePath];//让数据库路径成为第一响应者

    //选中第一行,sqlite to enity
    [self.functionTable selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];

 
    
    

    //[self.rootView addSubview: self.remindIngView];
    
    
}



-(void)addPlistJsonVCWithIndex:(NSInteger)index{


//    if (!_plistJsonVC) {
//       
//        [self.window makeFirstResponder:self.plistJsonVC.sqlitePath];//让数据库路径成为第一响应者
//    }
    

switch (index) {
    case 0:
        [self.plistJsonVC.view setHidden:YES];
        [self.sqlVC.view setHidden:NO];

        break;
    case 1:
        self.plistJsonVC.exportPlist=YES;
        [self.plistJsonVC configTheExportDesWith:NSLocalizedString(@"plistExportConfig des", nil)];
        [self.window.contentView addSubview:self.plistJsonVC.view];
        [self.window makeFirstResponder:self.plistJsonVC.sqlitePath];
        [self.plistJsonVC.view setHidden:NO];
        [self.sqlVC.view setHidden:YES];
        break;
    case 2:
        self.plistJsonVC.exportPlist=NO;
        [self.plistJsonVC configTheExportDesWith:NSLocalizedString(@"jsonExportConfig des", nil)];
        [self.window.contentView addSubview:self.plistJsonVC.view];
        [self.window makeFirstResponder:self.plistJsonVC.sqlitePath];
        [self.plistJsonVC.view setHidden:NO];
        [self.sqlVC.view setHidden:YES];
        break;
    default:
        break;
}

}




#pragma  -----tableview delegate & datasource------
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    if (tableView==self.functionTable) {
        return [_functionDataSource count];
    }
    
    return [_supportDataSource count];
    
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    // Used by bindings on the NSTableCellView's objectValue
    NSDictionary * item;
    
    if (tableView==self.functionTable) {
        item = [_functionDataSource objectAtIndex:row];
    } else {
    
     item = [_supportDataSource objectAtIndex:row];
    }
    
    return item;
}

- (void)tableViewSelectionDidChange:(NSNotification *)notification {
    // Bold the text in the selected items, and unbold non-selected items
    
    NSTableView * tableview=[notification object];
    
    if (tableview==self.supportTable) {
        
        
        //无论取消选择还是选择,这个方法都会触发一次.所以当没有选择时,针对某个表不让往下走
        NSIndexSet * selectindexset= [self.supportTable selectedRowIndexes];
        if ([selectindexset count]==0) {
            return;
        }
        
         //debugLog(@"select row:%d",[self.supportTable selectedRow]);
        [self.controllerSet removeAllObjects];
        [self supportTableActionWithIndex:[self.supportTable selectedRow]];
        [self.supportTable deselectAll:nil];
        return;
    }
    
    
    [self.functionTable enumerateAvailableRowViewsUsingBlock:^(NSTableRowView *rowView, NSInteger row) {
        // Enumerate all the views, and find the NSTableCellViews.
        // This demo could hard-code things, as it knows that the first cell is always an
        // NSTableCellView, but it is better to have more abstract code that works
        // in more locations.
        //
        
        //第几行第几列
        for (NSInteger column = 0; column < rowView.numberOfColumns; column++) {
            NSView *cellView = [rowView viewAtColumn:column];
            // Is this an NSTableCellView?
            if ([cellView isKindOfClass:[NSTableCellView class]]) {
                NSTableCellView *tableCellView = (NSTableCellView *)cellView;
                // It is -- grab the text field and bold the font if selected
                NSTextField *textField = tableCellView.textField;
                NSInteger fontSize = [textField.font pointSize];
                if (rowView.selected) {
                    textField.font = [NSFont boldSystemFontOfSize:fontSize];
                    textField.textColor=[NSColor blackColor];
                } else {
                    textField.font = [NSFont systemFontOfSize:fontSize];
                    textField.textColor=[NSColor whiteColor];
                }
            }
        }
    }];
    
    [self addPlistJsonVCWithIndex:[self.functionTable selectedRow]];
    
    
    //debugLog(@"ddsdsd");
}


-(void)supportTableActionWithIndex:(NSInteger)index{



    switch (index) {
        case 0:{
            
            for (id controller in self.controllerSet) {
                if ([controller isKindOfClass:[TutorialWindowController class]]) {
                    TutorialWindowController * twr=(TutorialWindowController*)controller;
                     [twr showWindow:self];
                    return;
                }
            }
            
            TutorialWindowController * twr=[[TutorialWindowController alloc] initWithWindowNibName:@"TutorialWindowController"];
            [self.controllerSet addObject:twr];
            [twr showWindow:self];
            
            
            
        }
            break;
        case 1:
            [self SupportEmail];
            break;
        case 2:
            [NSApp orderFrontStandardAboutPanel:nil];
            break;
        default:
            break;
    }


}



//弹出 email
-(void)SupportEmail{
    
    
    //版本更新
    NSDictionary *_infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString * currentversion = [_infoDictionary valueForKey:@"CFBundleVersion"];
 
    //subject
    NSString * subjectStr=[NSString stringWithFormat:@"suggestion about sqlite export tool(%@)",currentversion];
    
    NSString *mailtoAddress = [[NSString stringWithFormat:@"mailto:%@?Subject=%@&body=%@",@"hament@126.com",subjectStr,@"i have some suggestion about sqlite export tool:"] stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    
    
   [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:mailtoAddress]];


}

- (IBAction)sendEmail:(NSButton *)sender {
    
    NSImage *image = [NSImage imageNamed:@"logo_h"];
    NSString * des=[NSString stringWithFormat:@"%@ download:%@",NSLocalizedString(@"share Des", nil),ItunesLink];
    NSMutableArray *shareItems = [[NSMutableArray alloc] initWithObjects:des,image, nil];
    NSSharingService *tweetSharingService = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
    tweetSharingService.delegate = self;
    
    //加上改判断的话,如果系统没有twitter账户,则不会弹出界面
    // if ([tweetSharingService canPerformWithItems:shareItems]) {
    [tweetSharingService performWithItems:shareItems];
}




- (IBAction)sendTwitter:(NSButton *)sender {
    NSImage *image = [NSImage imageNamed:@"logo_h"]; 
    NSString * des=[NSString stringWithFormat:@"%@",NSLocalizedString(@"tw share Des", nil)];
    
    
    NSMutableArray *shareItems = [[NSMutableArray alloc] initWithObjects:des,[NSURL URLWithString:ItunesLink],image, nil];
    NSSharingService *tweetSharingService = [NSSharingService sharingServiceNamed:NSSharingServiceNamePostOnTwitter];
    tweetSharingService.delegate = self;
    //tweetSharingService.
    
    //加上改判断的话,如果系统没有twitter账户,则不会弹出界面
   // if ([tweetSharingService canPerformWithItems:shareItems]) {
        [tweetSharingService performWithItems:shareItems];
    //}
     
    
}




- (IBAction)sendFb:(NSButton *)sender {
    
    //NSImage *image = [NSImage imageNamed:@"logo_h"];
    
    //facebook会自动分析itunes的link,会显示icon,和链接
    
    NSString * des=[NSString stringWithFormat:@"%@. download:",NSLocalizedString(@"share Des", nil)];
    NSMutableArray *shareItems = [[NSMutableArray alloc] initWithObjects:des,[NSURL URLWithString:ItunesLink], nil];
    
    NSSharingService *tweetSharingService = [NSSharingService sharingServiceNamed:NSSharingServiceNamePostOnFacebook];
    tweetSharingService.delegate = self;
    
    //加上改判断的话,如果系统没有twitter账户,则不会弹出界面
    // if ([tweetSharingService canPerformWithItems:shareItems]) {
    [tweetSharingService performWithItems:shareItems];
    //}
    
}





- (IBAction)sendWb:(NSButton *)sender {
    
    NSImage *image = [NSImage imageNamed:@"logo_h"];
    NSString * des=[NSString stringWithFormat:@"%@ download:",NSLocalizedString(@"share Des", nil)];
    NSMutableArray *shareItems = [[NSMutableArray alloc] initWithObjects:des,[NSURL URLWithString:ItunesLink],image, nil];
    
    NSSharingService *tweetSharingService = [NSSharingService sharingServiceNamed:NSSharingServiceNamePostOnSinaWeibo];
    tweetSharingService.delegate = self;
    
    //加上改判断的话,如果系统没有twitter账户,则不会弹出界面
    // if ([tweetSharingService canPerformWithItems:shareItems]) {
    [tweetSharingService performWithItems:shareItems];
    //}
    
    
}



//添加和移除全局提示
-(void)addGlobalRemind{

    dispatch_block_t block= ^{
    //隐藏done图片
    [self.doneImgView setHidden:YES];
    [self.spinindicator setHidden:NO];
    
    //remind view
    self.remindIngView.frame=NSMakeRect(10,100 ,self.remindIngView.frame.size.width ,self.remindIngView.frame.size.height);
    
    //启动提示
    [self.spinindicator startAnimation:self];
    self.remindTv.string=NSLocalizedString(@"Processing.....", nil);
    self.remindTv.textColor=[NSColor whiteColor];
    [self.rootView addSubview:self.remindIngView positioned:NSWindowAbove relativeTo:nil];
       // [self.rootView addSubview:self.remindIngView ];
};
    
    dispatch_queue_t main = dispatch_get_main_queue();
    if (dispatch_get_current_queue() == main){
        block(); // execute the block directly, as main is already the current active queue
    }
    else {
        dispatch_async(main, block);
    }
    
}



-(void)finishProcessing{

    [self.doneImgView setHidden:NO];
    [self.spinindicator setHidden:YES];
    self.remindTv.string=NSLocalizedString(@"Done",nil);
     [self.spinindicator stopAnimation:self];
    
    [self performSelector:@selector(removeGlobalRemind) withObject:nil afterDelay:1.5];

}

-(void)removeGlobalRemind{

    
    
    NSRect startFrame = [self.remindIngView frame];
    NSRect endFrame = NSMakeRect(10, -300, self.remindIngView.frame.size.width, self.remindIngView.frame.size.height);
    NSDictionary *dictionary = @{NSViewAnimationTargetKey:self.remindIngView,
                                 NSViewAnimationEffectKey:NSViewAnimationFadeInEffect,
                                 NSViewAnimationStartFrameKey:[NSValue valueWithRect:startFrame],
                                 NSViewAnimationEndFrameKey:[NSValue valueWithRect:endFrame],
                                 @"des":@"RemindViewDisappear"};
    
    
    
    NSViewAnimation *animation = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dictionary]];
    //animation.delegate = self;
    animation.duration = 0.3;
    //NSAnimationBlocking阻塞
    //NSAnimationNonblocking异步不阻塞
    //NSAnimationNonblockingThreaded线程不阻塞
    [animation setAnimationBlockingMode:NSAnimationNonblocking];
    animation.delegate=self;
    [animation startAnimation];


}

#pragma animation ----delegate---
- (void)animationDidStop:(NSAnimation*)animation{
//    NSString * key=[animation key];
//    
//    NSArray * animations=[animation viewAnimations];
//    if ([key isEqualToString:@"RemindViewDisappear"]) {
         [self.remindIngView removeFromSuperview];
//    }


}




- (NSRect) sharingService: (NSSharingService *) sharingService
sourceFrameOnScreenForShareItem: (id<NSPasteboardWriting>) item
{
    if([item isKindOfClass: [NSURL class]])
    {
        //return a rect from where the image will fly
        return NSZeroRect;
    }
    
    return NSZeroRect;
}




@end
